package com.hospital.endescryption.module.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hospital.common.core.constants.InsuranceDeptEnum;
import com.hospital.common.core.exception.ExceptionHelp;
import com.hospital.common.core.exception.ExceptionPrint;
import com.hospital.common.core.module.entity.NFC.NFCResponse;
import com.hospital.common.core.module.entity.NFC.ORG_RES;
import com.hospital.common.core.result.ErrorTip;
import com.hospital.common.core.result.SuccessTip;
import com.hospital.common.core.result.Tip;
import com.hospital.common.core.utils.HseEncAndDecUtil;
import com.hospital.common.core.utils.Sm3Demo;
import com.hospital.endescryption.async.WxPayFunc;
import com.hospital.endescryption.config.properties.InsurProperties;
import com.hospital.endescryption.module.entity.EncryptionDecryptionDict;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;

@Slf4j
@RestController
@RequestMapping("/desctrytion")
public class desctrytionController {
    @Resource
    private InsurProperties insurProperties;
    @Resource
    private WxPayFunc wxPayFunc;

    @Autowired
    private enctrytionController enctrytionController;

    /**
     * 支付宝及人保返回解密接口
     *
     * @param requestVal
     * @param request
     * @return
     */
    @PostMapping(value = "/insurance", produces = {"application/json;charset=UTF-8"})
    public NFCResponse getorgone(@RequestBody NFCResponse requestVal, HttpServletRequest request) {

        ORG_RES tip = null;
        NFCResponse nfcResponse = null;
        String descryption = null;
        //第一层参数校验
        try {
            tip = wxPayFunc.validateFunc(requestVal);
            if (tip.getRet_code().equals(InsuranceDeptEnum.SUCCESS_HOS.getCode())) {
//                入参为密文时使用
                EncryptionDecryptionDict encryptionDecryptionDict = enctrytionController.getBySql(requestVal.getDataType(),requestVal.getChannel(),requestVal.getFromApp(),requestVal.getToApp());
                if (!requestVal.getSignType().equals(insurProperties.getSingTypeHis())) {
                    JSONObject denc = Sm3Demo.denc(JSON.parseObject(JSON.toJSONString(requestVal)),encryptionDecryptionDict.getAppId(),encryptionDecryptionDict.getAppSecret());
                    tip= new ORG_RES(denc);
                }else {
                 Tip   tipOld= wxPayFunc.getLastClass(JSON.parseObject(JSON.toJSONString(requestVal)), encryptionDecryptionDict.getAppId(), encryptionDecryptionDict.getAppSecret(),
                            encryptionDecryptionDict.getPlatformPublicKey());
                    tip.setData(tipOld.getData());
                    tip.setRet_code(String.valueOf(tipOld.getCode()));
                    tip.setRet_msg(tipOld.getMessage());
                }
            }
        } catch (ExceptionHelp e) {
            tip = new ORG_RES(InsuranceDeptEnum.HOS_ERROR, e.getMessage());
        } catch (Exception e) {
            tip = new ORG_RES(InsuranceDeptEnum.FILED_REQ_BILL_SERVER, e.getMessage());
        } finally {
            nfcResponse = new NFCResponse();
            nfcResponse.setSignType(insurProperties.getSingTypeHis());
            nfcResponse.setEncType(insurProperties.getEncryptType());
            nfcResponse.setVersion(insurProperties.getVersion());
            nfcResponse.setCode(0);
            nfcResponse.setAppId(insurProperties.getAppIdInsur());
            long timeInMillis = Calendar.getInstance().getTimeInMillis();
            nfcResponse.setTimestamp(String.valueOf(timeInMillis));
            nfcResponse.setData(tip.getData());
            nfcResponse.setMessage(tip.getRet_msg());
            ExceptionPrint.printCommErrorString("解密接口",
                    JSON.toJSONString(requestVal),
                    String.valueOf(tip.getRet_code())
                    , tip.getRet_msg(), "", "返回给接口解密数据：" + JSON.toJSONString(nfcResponse), descryption, "", "");
        }
        return nfcResponse;
    }

    /**
     * 微信及电子处方上传返回解密接口
     *
     * @param requestVal
     * @return
     */
    @PostMapping(value = "/insurWeChatPresc", produces = {"application/json;charset=UTF-8"})
    public Tip getorgone(@RequestBody NFCResponse requestVal) {
        Tip tip = null;
        EncryptionDecryptionDict encryptionDecryptionDict = enctrytionController.getBySql(requestVal.getDataType(),requestVal.getChannel(),requestVal.getFromApp(),requestVal.getToApp());
        JSONObject jsonObject = null;
        try {
            String s = HseEncAndDecUtil.decryptMsg(JSON.parseObject(requestVal.getData().toString()),
                    encryptionDecryptionDict.getAppSecret(), encryptionDecryptionDict.getPlatformPublicKey(), encryptionDecryptionDict.getAppId());
            jsonObject = JSON.parseObject(s);
            tip = new SuccessTip();
            tip.setData(jsonObject);
        } catch (Exception e) {
            tip =  new ErrorTip(303,e.getMessage());
        }finally {
            ExceptionPrint.printCommErrorString("解密接口",
                    JSON.toJSONString(requestVal),
                    String.valueOf(tip.getCode())
                    , tip.getMessage(), "", "返回给接口加密数据：" + jsonObject, "", "", "");
        }
        return tip;
    }
}
